package com.example.computer_component_manager.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.computer_component_manager.R
import com.example.computer_component_manager.adapter.BrandAdapter
import com.example.computer_component_manager.bean.AllCpuInfo
import com.example.computer_component_manager.bean.Brand
import com.example.computer_component_manager.bean.Brands
import com.example.computer_component_manager.fragment.impl.CpuFragment
import com.example.computer_component_manager.util.DbUtil
import com.example.computer_component_manager.util.ToastUtil
import com.example.computer_component_manager.volley.MyJsonObjectRequest
import com.example.computer_component_manager.volley.VolleyApplication
import com.example.computer_component_manager.databinding.ActivityCpuEditorBinding
import com.google.gson.Gson
import org.json.JSONObject

/**
 * CPU编辑器(Activity)
 * 采用binding方法访问视图
 *
 * @author 1923111015董寺卓
 */
class CpuEditorActivity : AppCompatActivity() {

    private lateinit var binding: ActivityCpuEditorBinding

    // 表单默认值
    private var cpu = AllCpuInfo.CpuInfoItem(Brand(1, ""),
        1, 0.0,
        0, 1, 1.0,
        0, 1, "")

    // 品牌默认位置
    private var brandPosition: Int = 0

    // 品牌列表
    private lateinit var brands: Brands

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCpuEditorBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 获取CPU信息的位置
        val cpuItemPosition = intent.getIntExtra("cpuItemPosition", -1)
        // 如果获取到CPU信息，则覆盖默认值（ID也更改）
        if (cpuItemPosition > -1) {
            cpu = CpuFragment.allCpuInfo[cpuItemPosition]
        }
        // 使用intent获取CPU品牌信息
        val allBrandsJsonStr = intent.getStringExtra("cpuBrands")
        brands = DbUtil.gson.fromJson(allBrandsJsonStr, Brands::class.java)
        val cpuBrandAdapter = BrandAdapter(this, brands)
        binding.spinnerBrand.adapter = cpuBrandAdapter
        // 选中品牌
        if (cpuItemPosition > -1) {
            for ((index, e) in brands.withIndex()) {
                if (e.id == cpu.brand.id)
                    binding.spinnerBrand.setSelection(index)
            }
        }
        binding.etCpuEditorType.setText(cpu.type)
        binding.etCpuEditorLithography.setText(cpu.lithography.toString())
        binding.etCpuEditorPrice.setText(cpu.customerPrice.toString())
        binding.etCpuEditorMaxTurboFreq.setText(cpu.maxTurboFrequency.toString())
        binding.etCpuEditorCoreNumber.setText(cpu.coreNumber.toString())
        binding.etCpuEditorThreadNumber.setText(cpu.threadNumber.toString())
        // 点击选中事件
        binding.spinnerBrand.onItemSelectedListener =
            object : AdapterView.OnItemSelectedListener {

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View,
                    position: Int,
                    id: Long,
                ) {
                    binding.spinnerBrand.setSelection(position)
                    this@CpuEditorActivity.brandPosition = position
                    Log.d("Select", binding.spinnerBrand.selectedItemPosition.toString())
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    Toast.makeText(this@CpuEditorActivity,
                        resources.getString(R.string.nothing_selected),
                        Toast.LENGTH_SHORT).show()
                }
            }
    }

    /**
     * 提交更新方法
     */
    fun submit(view: View) {
        if (view.id == R.id.btnCpuEditorSubmit) {
            val cpu = AllCpuInfo.CpuInfoItem(brands[brandPosition],
                binding.etCpuEditorCoreNumber.text.toString().toInt(),
                binding.etCpuEditorPrice.text.toString().toDouble(),
                cpu.id, binding.etCpuEditorLithography.text.toString().toInt(),
                binding.etCpuEditorMaxTurboFreq.text.toString().toDouble(), cpu.stock,
                binding.etCpuEditorThreadNumber.text.toString().toInt(),
                binding.etCpuEditorType.text.toString())

            val reqJsonObject = JSONObject(Gson().toJson(cpu))
            val myJsonObjectRequest =
                MyJsonObjectRequest(DbUtil.UPDATE, "${DbUtil.API_PREFIX}/cpu/${cpu.id}",
                    reqJsonObject, {
                        Log.d("TAG", "submit: $it")
                        this.setResult(RESULT_OK)
                        finish()
                    }, {
                        ToastUtil.showShortError(this)
                        this.setResult(RESULT_CANCELED)
                    })
            VolleyApplication.instance.requestQueue.add(myJsonObjectRequest)

        }
    }

}